package com.itheima.leyou.dao;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Repository
public class UserDao {

    @Resource
    JdbcTemplate jdbcTemplate;

    public ArrayList<Map<String, Object>> getUser(String phone, String password){
        String sql = "select username, phone from tb_user where phone = '"+phone+"'";
        return (ArrayList<Map<String,Object>>) jdbcTemplate.queryForList(sql);
    }

    public Map<String, Object> insertUser(String username, String phone, String password){
        String sql = "select id from tb_user where phone = '"+phone+"'";

        ArrayList<Map<String, Object>> list = new ArrayList<>();
        list = (ArrayList<Map<String,Object>>) jdbcTemplate.queryForList(sql);
        Map<String, Object> result = new HashMap<>();

        if (!list.isEmpty()){
            result.put("result", false);
            result.put("msg", "已经存在手机号为["+phone+"]的用户！");
            return result;
        }

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sql = "insert into tb_user (username, password, phone, create_time) values "+
            "('"+username+"', '"+password+"', '"+phone+"', '"+simpleDateFormat.format(new Date())+"')";
        if (jdbcTemplate.update(sql)==1){
            result.put("result", true);
            result.put("msg", "");
        }else {
            result.put("result", false);
            result.put("msg", "写入用户表时出错！");
        }
        return result;
    }

}
